<?php

namespace App\Http\Controllers\App;

use App\Http\Controllers\Controller;
use App\Permission;
use App\Role;
use Illuminate\Http\Request;

class PermissionController extends Controller
{

    public function index(Request $request, $role_id)
    {
        $role = Role::find($role_id);
        $perms = $role->perms()->paginate(10);
        return view('permission.index', [
            'perms' => $perms,
            'role'=>$role
        ]);
    }

    public function assign(Request $request, $role_id)
    {
        $role = Role::find($role_id);
        $perm_ids = array_pluck($role->perms()->get(['id'])->toArray(), 'id');
        $otherPerms = Permission::whereNotIn('id', $perm_ids)->get();
        $datas = $otherPerms->mapWithKeys(function ($item) {
            return [$item['id'] => $item['display_name']];
        });
        return view('permission.assign', [
            'perms' => $datas,
            'role' => $role
        ]);
    }

    public function show(Request $request,$permission_id)
    {
        return view('permission.show',[
            'permission'=>Permission::find($permission_id)
        ]);
    }

    public function assignCheck(Request $request, $role_id)
    {
        $role = Role::find($role_id);
        $permission =  Permission::find($request->input('permission_id'));
        if($role&&$permission)
            $role->attachPermission($permission);
        return redirect()->route('permission.index',['role_id'=>$role_id]);
    }

    public function unassign(Request $request, Role $role, Permission $permission)
    {
        if($role&&$permission)
            $role->detachPermission($permission);
        return redirect()->route('permission.index',['role_id'=>$role->id]);
    }
}